#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice
import sys, os, thread

try:
    HOME = os.environ['FIPA']
except KeyError:
    print 'FIPA environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE1 = os.path.join(SLICE, 'FIPA.ice')
Ice.loadSlice('--all -I/usr/share/slice', ['-I' + SLICE, FILE1])

import FIPA

class AMSI (FIPA.AMS):

    def __init__ (self, platformName):
        # Key   ==> Object identity.
        # Value ==> Agent's AID (see FIPATypes.ice).
        self.__agents = {}
        self.__mutex = thread.allocate_lock()
        # TODO: include the MTS's address in the ApDescription.
        self.__apDescription = FIPA.ApDescription(platformName)

    # Register a new agent in the agent platform.
    def register (self, aid, curr):
        self.__mutex.acquire()
        if self.__agents.has_key(aid.ice_getIdentity()):
            self.__mutex.release()
            raise FIPA.AgentExists
        else:            
            self.__agents[aid.ice_getIdentity()] = aid
            #print str(aid.ice_getIdentity().name) + ' registered with the AMS.'
            self.__mutex.release()

    # Deregister a new agent in the agent platform.
    def deregister (self, id, curr = None):
        self.__mutex.acquire()
        try:
            self.__agents.pop(id)
            #print str(id.name) + ' deregistered with the AMS.'
            self.__mutex.release()
        except KeyError:
            pass

    def search (self, id, curr = None):
        try:
            return self.__agents[id]
        except KeyError:
            return None

    def getDescription (self, curr = None):
        return self.__apDescription
